﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.IO;
using System.Web.UI.HtmlControls;

namespace ReportTracking.ServiceLoadControl
{
    /// <summary>
    /// Summary description for ScriptService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class ScriptService : System.Web.Services.WebService
    {

        public ScriptService()
        {
            //Uncomment the following line if using designed components 
            //InitializeComponent(); 
        }

        /// <summary>
        /// Get User Control Html
        /// use EnableSession=true if you are using session variables
        /// </summary>
        /// <returns>Html Table</returns>
        [WebMethod(EnableSession = true)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetControlHtml(string controlLocation, object Para)
        {
            // Create instance of the page control
            Page page = new Page();

            // Create instance of the user control
            //CTemplateUserControl userControl = (CTemplateUserControl)page.LoadControl(controlLocation);
            //userControl.Data = Para;

            //Disabled ViewState- If required
            //userControl.EnableViewState = false;

            //Form control is mandatory on page control to process User Controls
            HtmlForm form = new HtmlForm();

            UserControl userControl = (UserControl)page.LoadControl(controlLocation);
            //Add user control to the form
            form.Controls.Add(userControl);

            //Add form to the page 
            page.Controls.Add(form);

            //Write the control Html to text writer
            StringWriter textWriter = new StringWriter();

            //execute page on server 
            HttpContext.Current.Server.Execute(page, textWriter, false);

            // Clean up code and return html
            return CleanHtml(textWriter.ToString());

        }

        /// <summary>
        /// Removes Form tags using Regular Expression
        /// </summary>
        private string CleanHtml(string html)
        {
            return Regex.Replace(html, @"<[/]?(form)[^>]*?>", "", RegexOptions.IgnoreCase);
        }
    }
}
